#!/usr/bin/env python3
import sys, os
import argparse
import yaml  # pip install pyyaml
import logging
logging.basicConfig(stream=sys.stderr, level=logging.INFO, format='%(asctime)s [%(levelname)s] %(message)s')

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('resource_type', choices=['model', 'dataset'])
    parser.add_argument('resource_id', type=str, help='submission model/dataset id')
    args = parser.parse_args()
    logging.info(args)

    if not os.path.isfile('utils/oss'):
        logging.error("Please install oss via utils/install_aliyun_oss_client.sh")
        sys.exit(-1)

    if not os.path.isfile('credentials/aliyun_oss.cfg'):
        instructions_to_get_credential = (
            'You need credential to use the leaderboard:\n  '
            'Please send email with title "oss.cfg" to leaderboard@speechio.ai, '
            'and paste replied content to credentials/aliyun_oss.cfg'
        )
        logging.error(instructions_to_get_credential)
        sys.exit(-1)

    model_zoo = 'models'
    dataset_zoo = 'datasets'

    if args.resource_type == 'model':
        model_id = args.resource_id
        with open(os.path.join(model_zoo, 'zoo.yaml'), 'r', encoding='utf8') as f:
            remote_model_zoo = yaml.safe_load(f)
        src = remote_model_zoo[model_id]['url']
        dst = os.path.join(model_zoo, model_id)

    elif args.resource_type == 'dataset':
        dataset_id = args.resource_id
        with open(os.path.join(dataset_zoo, 'zoo.yaml'), 'r', encoding='utf8') as f:
            remote_dataset_zoo = yaml.safe_load(f)
        src = remote_dataset_zoo[dataset_id]['url']
        dst = os.path.join(dataset_zoo, dataset_id)

    else:
        raise NotImplementedError

    cmd = F'utils/oss -c credentials/aliyun_oss.cfg cp -ur {src} {dst}'
    logging.info(cmd)
    os.system(cmd)
